<template>
  <div class="container">
    <el-card shadow="always">
      <!-- 标题部分 -->
      <el-row type="flex">
        <el-col>
          <span>试题录入</span>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <!-- 放置表单 -->
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-position="left"
        label-width="120px"
        style="margin: 30px 0 20px 0"
      >
        <el-form-item label="学科：" prop="subjectID">
          <el-select
            v-model="ruleForm.subjectID"
            style="width: 400px"
            @change="changeSubjectID"
          >
            <el-option
              :label="item.label"
              v-for="item in simpleList"
              :key="item.value"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="ruleForm.catalogID" style="width: 400px">
            <el-option
              :label="item.label"
              v-for="item in catalogList"
              :key="item.value"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="企业：" prop="enterpriseID">
          <el-select v-model="ruleForm.enterpriseID" style="width: 400px">
            <el-option
              :label="item.company"
              v-for="item in enterpriseList"
              :key="item.id"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="城市：" required>
          <el-row type="flex" style="width: 400px">
            <el-col>
              <el-form-item prop="province">
                <el-select v-model="ruleForm.province" style="width: 98%">
                  <el-option
                    v-for="(item, index) in provincesList"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col>
              <el-form-item prop="city">
                <el-select v-model="ruleForm.city" style="width: 100%">
                  <el-option
                    v-for="(item, index) in citysList"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="方向：" prop="direction">
          <el-select v-model="ruleForm.direction" style="width: 400px">
            <el-option
              v-for="(item, index) in directionList"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="题型：" prop="questionType">
          <el-radio-group
            v-model="ruleForm.questionType"
            @change="questionTypeChange"
            style="width: 400px"
          >
            <el-radio
              v-for="(item, index) in questionTypeList"
              :key="index"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="ruleForm.difficulty" style="width: 400px">
            <el-radio
              v-for="(item, index) in difficultyList"
              :key="index"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <el-form-item label="题干：" prop="question">
          <QuillEditor
            style="minwidth: 666px"
            :content.sync="ruleForm.question"
          ></QuillEditor>
        </el-form-item>

        <!-- 如果题型为单选状态下显示 -->
        <el-form-item
          v-if="ruleForm.questionType === 1"
          label="选项："
          prop="option"
        >
          <el-radio-group v-model="optionValue" style="width: 500px">
            <el-row
              type="flex"
              justify="space-between"
              v-for="(item, index) in ruleForm.options"
              :key="index"
            >
              <el-col>
                <el-radio :label="item.code" style="margin-bottom: 35px"
                  >{{ item.code }} :
                  <el-input style="margin-left: 5px" v-model="item.title">
                  </el-input>
                </el-radio>
              </el-col>
              <el-col style="margin: -10px 0 0 55px">
                <!-- 上传图片文件 -->
                <el-upload
                  class="avatar-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :on-error="handleAvatarError"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="item.img" :src="item.img" class="avatar" />
                  <span
                    @click="getImgIndex(index)"
                    v-else
                    class="avatar-uploader-icon"
                  >
                    上传图片
                  </span>
                </el-upload>
              </el-col>
            </el-row>
          </el-radio-group>

          <div>
            <el-button type="danger" disabled @click="addOptionItem"
              >+增加选项与答案</el-button
            >
          </div>
        </el-form-item>

        <!-- 如果题型为多选状态下显示 -->
        <el-form-item
          v-if="ruleForm.questionType === 2"
          label="选项："
          prop="option"
        >
          <el-checkbox-group v-model="optionValueList" style="width: 630px">
            <el-row
              type="flex"
              justify="space-between"
              v-for="(item, index) in ruleForm.options"
              :key="index"
            >
              <el-col>
                <el-checkbox :label="item.code" style="margin-bottom: 35px"
                  >{{ item.code }} :
                  <el-input
                    style="margin-left: 5px; width: 250px"
                    v-model="item.title"
                  ></el-input>
                </el-checkbox>
              </el-col>
              <el-col style="margin: -10px 0 0 0px">
                <!-- 上传图片文件 -->
                <el-upload
                  class="avatar-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :on-error="handleAvatarError"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="item.img" :src="item.img" class="avatar" />
                  <span
                    @click="getImgIndex(index)"
                    v-else
                    class="avatar-uploader-icon"
                  >
                    上传图片
                  </span>
                </el-upload>
              </el-col>
            </el-row>
          </el-checkbox-group>

          <div>
            <el-button type="danger" @click="addOptionItem"
              >+增加选项与答案</el-button
            >
          </div>
        </el-form-item>

        <el-form-item label="解析视频：" prop="videoURL">
          <el-input v-model="ruleForm.videoURL" style="width: 400px">
          </el-input>
        </el-form-item>

        <el-form-item label="答案解析：" prop="answer">
          <QuillEditor
            style="minwidth: 666px"
            :content.sync="ruleForm.answer"
          ></QuillEditor>
        </el-form-item>

        <el-form-item label="题目备注：" prop="remarks">
          <el-input
            v-model="ruleForm.remarks"
            type="textarea"
            style="width: 400px"
          ></el-input>
        </el-form-item>

        <el-form-item label="试题标签：" prop="tags">
          <el-select
            v-model="tagsSelectList"
            placeholder="请选择试题标签"
            style="width: 400px"
            multiple
            @change="ruleForm.tags = tagsSelectList.join(',')"
          >
            <el-option
              v-for="(item, index) in tagsList"
              :key="index"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitBtn">确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import QuillEditor from "../components/quillEditor/index.vue"; // 引入富文本组件
import { simple } from "@/api/hmmm/subjects"; // 获取学科简单列表
import { simple as catalogListAPI } from "@/api/hmmm/directorys"; // 获取学科简单列表
import { list as enterpriseListAPI } from "@/api/hmmm/companys"; // 获取企业列表api
import { provinces, citys } from "@/api/hmmm/citys"; // 枚举文件 城市列表和相对应的县区列表
import { direction, difficulty, questionType } from "@/api/hmmm/constants"; // 枚举文件  方向列表
import { simple as tagsListAPI } from "@/api/hmmm/tags"; // 获取标签简单列表
import {
  add as addQuestionsAPI,
  update as putQuestionsAPI,
  detail as getQuestionsAPI,
} from "@/api/hmmm/questions"; // 引入 基础题库增加方法
// import { ImageUpload } from "../components/ImageUpload/index.vue";
export default {
  components: {
    QuillEditor, // 富文本组件
  },
  data() {
    return {
      imgIndex: "", // 存储点击上传标签的索引
      ruleForm: {
        // 表单绑定数据
        subjectID: "", // 学科
        catalogID: "", // 目录
        enterpriseID: "", // 企业
        province: "", // 城市
        city: "", // 地区
        direction: "", // 方向
        questionType: 1, // 题型
        difficulty: 1, // 难度
        question: "4444", //  题干
        options: [
          {
            // 选项
            code: "A", //  代码
            title: "", // 标题
            img: "", // 图片路径
            isRight: false, // 是否正确答案  boolean类型
          },
          {
            code: "B", //  代码
            title: "", // 标题
            img: "", // 图片路径
            isRight: false, // 是否正确答案  boolean类型
          },
          {
            code: "C", //  代码
            title: "", // 标题
            img: "", // 图片路径
            isRight: false, // 是否正确答案  boolean类型
          },
          {
            code: "D", //  代码
            title: "", // 标题
            img: "", // 图片路径
            isRight: false, // 是否正确答案  boolean类型
          },
        ],
        videoURL: "", // 解析视频
        answer: "", // 答案解析
        remarks: "", // 题目备注
        tags: "", //  试题标签
      },
      rules: {
        // 表单验证规则
        subjectID: [
          { required: true, message: "请选择学科", trigger: "change" },
        ],
        catalogID: [
          { required: true, message: "请选择目录", trigger: "change" },
        ],
        enterpriseID: [
          { required: true, message: "请选择企业", trigger: "change" },
        ],
        province: [
          { required: true, message: "请选择城市", trigger: "change" },
        ],
        city: [{ required: true, message: "请选择县区", trigger: "change" }],
        direction: [
          { required: true, message: "请选择发展方向", trigger: "change" },
        ],
        questionType: [
          { required: true, message: "请选择试题类型", trigger: "change" },
        ],
        difficulty: [
          { required: true, message: "请选择试题难度", trigger: "change" },
        ],
        question: [
          { required: true, message: "题干不能为空", trigger: "change" },
        ],
        answer: [
          { required: true, message: "答案解析不能为空", trigger: "change" },
        ],
      },
      simpleList: [], // 存储学科简单列表数据
      catalogList: [], // 存储目录列表
      enterpriseList: [], // 存储企业列表
      provincesList: [], // 存储城市列表
      citysList: [], // 存储城市下的县区列表
      directionList: [], // 存储方向列表
      difficultyList: [], //  存储难度列表
      questionTypeList: [], // 存储题型列表
      optionValue: "", // 存储单选状态下选中的选项
      optionValueList: [], // 存储多选状态下选中的选项集合
      tagsList: [], // 存储标签简单列表
      tagsSelectList: [], // 存储选中的标签集合
    };
  },

  created() {
    this.simple(); // 获取学科列表数据
    this.getEnterpriseList(); // 获取企业列表数据
    this.provincesList = provinces(); // 获取城市列表
    this.directionList = direction; // 获取方向列表
    this.difficultyList = difficulty; // 获取难度列表
    this.questionTypeList = questionType; // 获取题型列表
    if (this.$route.query.id) {
      // 判断路由是否有传递过来id
      this.getQuestions(); // 根据路由传递过来的的id 调用获取题库详情方法
    }
  },

  computed: {},
  watch: {
    // 侦听属性
    "ruleForm.province": {
      // 侦听城市变化
      handler(newValue, oldValue) {
        this.ruleForm.city = ""; // 城市改变 县区跟着改变
        //需要具体执行的方法
        this.citysList = citys(newValue);
      },
      deep: true, //是否深度监听，默认为false;监听器会一层一层的向下遍历，给对象的每一个属性添加一个监听器
      immediate: true, // 初始化监听
    },
    optionValue: {
      // 单选状态下 选中项的侦听事件
      handler(newValue, oldValue) {
        this.ruleForm.options.find(
          (item) => item.code === newValue
        ).isRight = true; // 找出选项数组中的选中项将该项的isRight属性设置为true
      },
    },
    optionValueList: {
      // d多选状态下 选中项的侦听事件
      handler(newValue, oldValue) {
        this.ruleForm.options.forEach((item) => (item.isRight = false)); // 每次切换题型都将选项的正确答案设置为false
        newValue.forEach(
          (val) =>
            (this.ruleForm.options.find(
              (item) => item.code === val
            ).isRight = true)
        );
      },
      deep: true, //是否深度监听，默认为false;监听器会一层一层的向下遍历，给对象的每一个属性添加一个监听器
    },
  },

  methods: {
    async simple() {
      // 获取学科简单列表
      const { data } = await simple();
      // console.log(data);
      this.simpleList = data;
    },
    async getCatalogList() {
      // 获取目录列表方法
      const { data } = await catalogListAPI({
        subjectID: this.ruleForm.subject,
      });
      // console.log(res);
      this.catalogList = data;
    },
    async getEnterpriseList() {
      // 获取企业列表方法
      const {
        data: { items },
      } = await enterpriseListAPI({ pagesize: 10000 });
      // console.log(items);
      this.enterpriseList = items;
    },
    addOptionItem() {
      // 增加选项与答案按钮点击事件
      this.ruleForm.options.push({
        // 选项
        code: String.fromCharCode(
          "A".charCodeAt(0) + this.ruleForm.options.length
        ), //  代码
        title: "", // 标题
        img: "", // 图片路径
        isRight: false, // 是否正确答案  boolean类型
      });
    },
    questionTypeChange() {
      // 题型切换事件 将正确答案清空
      this.optionValue = "";
      this.optionValueList = [];
      this.ruleForm.options.forEach((item) => (item.isRight = false)); // 每次切换题型都将选项的正确答案设置为false
    },
    async getTagsList() {
      // 获取标签简单列表方法
      const { data } = await tagsListAPI({
        subjectID: this.ruleForm.subjectID,
      }); // 发起获取标签简单列表请求
      this.tagsList = data;
    },
    changeSubjectID() {
      // 学科改变事件
      this.getCatalogList(); // 调用获取目录列表方法
      this.getTagsList(); // 调用获取标签简单列表方法
    },
    async submitBtn() {
      // 确认提交按钮
      try {
        await this.$refs.ruleForm.validate(); /// 重新呀验证表单
        if (!this.$route.query.id) {
          // 判断是否有
          await addQuestionsAPI({
            // 发起题库添加请求
            ...this.ruleForm,
            difficulty: this.ruleForm.difficulty.toString(),
            questionType: this.ruleForm.questionType.toString(),
          });
          this.$message.success("添加成功"); // 提示成功
        } else {
          await putQuestionsAPI({id: +this.$route.query.id,
            // 发起题库修改请求
            ...this.ruleForm,
            difficulty: this.ruleForm.difficulty.toString(),
            questionType: this.ruleForm.questionType.toString(),
          });
          this.$message.success("修改成功"); // 提示成功
        }
        this.ruleForm = {
          // 重置表单数据
          // 表单绑定数据
          subjectID: "", // 学科
          catalogID: "", // 目录
          enterpriseID: "", // 企业
          province: "", // 城市
          city: "", // 地区
          direction: "", // 方向
          questionType: 1, // 题型
          difficulty: 1, // 难度
          question: "", //  题干
          options: [
            {
              // 选项
              code: "A", //  代码
              title: "", // 标题
              img: "", // 图片路径
              isRight: false, // 是否正确答案  boolean类型
            },
            {
              code: "B", //  代码
              title: "", // 标题
              img: "", // 图片路径
              isRight: false, // 是否正确答案  boolean类型
            },
            {
              code: "C", //  代码
              title: "", // 标题
              img: "", // 图片路径
              isRight: false, // 是否正确答案  boolean类型
            },
            {
              code: "D", //  代码
              title: "", // 标题
              img: "", // 图片路径
              isRight: false, // 是否正确答案  boolean类型
            },
          ],
          videoURL: "", // 解析视频
          answer: "", // 答案解析
          remarks: "", // 题目备注
          tags: "", //  试题标签
        };
        await this.$refs.ruleForm.resetFields(); // 重置表单校验结果
        this.$router.push("/questions/list");
      } catch (error) {
        console.log(error);
      }
    },

    handleAvatarSuccess(res, file, fileList) {
      // 图片上传成功触发的事件
      // console.log(this.imgIndex);
      this.ruleForm.options[this.imgIndex].img = URL.createObjectURL(file.raw);

      // console.log(res);
      // console.log(file);
      // console.log(fileList);
    },
    beforeAvatarUpload(file) {
      // 上传文件之前触发的事件
      const isJPG =
        file.type === "image/jpeg/" || "image/png/" || "image/webp/";
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG/WEBP 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
      }
      return isJPG && isLt2M;
    },
    handleAvatarError(err) {
      console.log(err);
      // success(成功) 、warning(警告)、info(消息)、error(错误)
      this.$message.warning("年轻人，耗子尾汁！建议换张正方形图片试试🦖");
    },
    getImgIndex(index) {
      // 获取点击上传标签的索引方法
      this.imgIndex = index;
    },
    async getQuestions() {
      // 根据路由传递过来的id 获取题库详情
      try {
        const { data } = await getQuestionsAPI({ id: this.$route.query.id }); // 调用获取题库详情数据
        // console.log(data);
        this.ruleForm = {
          subjectID: data.subjectID || "", // 学科
          catalogID: data.catalogID || "", // 目录
          enterpriseID: data.enterpriseID || "", // 企业
          province: data.province || "", // 城市
          city: data.city || "", // 地区
          direction: data.direction || "", // 方向
          questionType: +data.questionType || 1, // 题型
          difficulty: +data.difficulty || 1, // 难度
          question: data.question || "", //  题干
          options: data.options || [
            {
              // 选项
              code: "A", //  代码
              title: "", // 标题
              img: "", // 图片路径
              isRight: false, // 是否正确答案  boolean类型
            },
            {
              code: "B", //  代码
              title: "", // 标题
              img: "", // 图片路径
              isRight: false, // 是否正确答案  boolean类型
            },
            {
              code: "C", //  代码
              title: "", // 标题
              img: "", // 图片路径
              isRight: false, // 是否正确答案  boolean类型
            },
            {
              code: "D", //  代码
              title: "", // 标题
              img: "", // 图片路径
              isRight: false, // 是否正确答案  boolean类型
            },
          ],
          videoURL: data.videoURL || "", // 解析视频
          answer: data.answer || "", // 答案解析
          remarks: data.remarks || "", // 题目备注
          tags: data.tags || "", //  试题标签
        };
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  padding: 20px;
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    display: inline-block;
    font-style: none !important;
    font-size: 12px;
    width: 60px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    border: 1px dashed #ccc;
    border-radius: 8px;
    overflow: hidden;
  }
  .avatar {
    width: 60px;
    height: 60px;
    display: block;
    border-radius: 8px;
    overflow: hidden;
  }
}
</style>
